// Initialize the jQuery no conflict to evade $ conflict usage with Prototype
function initPage() {
  var $jQ = jQuery.noConflict();
  initGameSelector($jQ);
  return $jQ;
}

// Add functionality to the game selector.
function initGameSelector($jQ) {
  $jQ(document).ready(function() {
    $jQ("#current_game").toggle(function() {
      $jQ('#game_selector .game_list').show();
    }, function() {
      $jQ('#game_selector .game_list').hide();
    });
  });
}

// Add draggable funtionality to order things
// (draggableBodyId) = jq selector syntax to indicate the body of the table to order
// (reorderPath) = url path in string where to post the final order
// (ommited) = class string to omit from the draggable
function initDraggable(draggableBodyId, reorderPath, ommited) {
  $jQ(document).ready(function() {
    $jQ("#" + draggableBodyId).sortable({
      handle: '.drag_handle',
      opacity: 0.6,
      items: "tr:not(" + ommited + ")",
      update: function() {
        var order = $jQ('#' + draggableBodyId).sortable('serialize');
        $jQ('.save_status').show();
        $jQ.post(reorderPath, order, function() {
          $jQ('.save_status').slideUp('slow');
        });
      }
    });
  });
}

// quick/live search filter JS component that is used by search_filter_bar defined in base_helper.rb
// (list_el) = jq selector syntax single list element to be evaluated(hide/show)
// (item) = jq selector syntax for defining the content to be matched inside the list_el
// (query_el) = query element(dom element not jq syntax) for the text field
function search_filter_bar(list_el, item, query_el) {
  var filter_results = $jQ(list_el).hide().filter(function() {
    return $jQ(item, this).html().search($jQ(query_el).val()) != -1;
  })
  filter_results.show();
  $jQ(query_el).next().next().html(filter_results.length + " matches.");
}

// Content Switching mechanism
// Required a "#additional_fields" and "#additional_fields #temp" in the view
// Look at  Virtual Goods Manager + Game Item form to see example.
// Don't forget to store the "other content" into the storage_box when you finished loading.
function switch_content(parent_box, storage_box) {
  var box = $jQ(parent_box);
  $jQ("#additional_fields #temp").html(box.html());
  box.html($jQ(storage_box).html());
  $jQ(storage_box).html($jQ("#additional_fields #temp").html());
}
